package cn.zz.veggie.application.packer;

import java.util.List;
import java.util.Map;
import java.util.Optional;

import cn.zz.comm.util.CollectorUtil;
import cn.zz.veggie.model.domain.DelMan;
import cn.zz.veggie.model.domain.Order;
import cn.zz.veggie.model.domain.OrderInfo;
import cn.zz.veggie.model.domain.Product;
import cn.zz.veggie.model.domain.Shop;
import cn.zz.veggie.web.types.vo.mgmt.MgmtOrderDetailVo;
import cn.zz.veggie.web.types.vo.mgmt.MgmtOrderItemVo;
import cn.zz.veggie.web.types.vo.mgmt.MgmtOrderVo;
import cn.zz.veggie.web.types.vo.mgmt.order.MgmtOrderBriefVo;

/**
 * @author zhongq
 * @since 2024/5/25
 */
public class OrderPacker {
	public static MgmtOrderVo toMgmtOrderVo(Order order, Shop shop, DelMan delMan) {
		final MgmtOrderVo vo = new MgmtOrderVo();
		injectOrderVo(vo, order, shop, delMan);

		return vo;
	}

	public static MgmtOrderDetailVo toOrderDetail(Order order, Shop shop, List<OrderInfo> orderItems,
			Map<Integer, Product> productMap, DelMan delMan) {
		final MgmtOrderDetailVo vo = new MgmtOrderDetailVo();
		injectOrderVo(vo, order, shop, delMan);
		vo.setItems(
				CollectorUtil.bwl(orderItems, item -> toMgmtOrderItemVo(item, productMap.get(item.getProductId()))));
		return vo;
	}

	public static MgmtOrderItemVo toMgmtOrderItemVo(OrderInfo item, Product product) {
		MgmtOrderItemVo vo = new MgmtOrderItemVo();
		vo.setId(item.getId());
		vo.setPrice(item.getPrice());
		vo.setRemark(item.getRemark());
		vo.setQuantity(item.getQuantity());
		vo.setShipped(item.getShipped());
		vo.setPrice(item.getPrice());
		vo.setAmount(item.getAmount());
		vo.setCreatedAt(item.getCreatedAt());
		vo.setUpdatedAt(item.getUpdatedAt());
		vo.setProduct(ProductPacker.toHisProductVo(product));

		return vo;
	}

	private static void injectOrderVo(MgmtOrderVo vo, Order o, Shop shop, DelMan delMan) {
		vo.setId(o.getId());
		vo.setSn(o.getSn());
		vo.setStatus(o.getStatus());
		vo.setAmount(o.getAmount());
		vo.setAddress(o.getAddress());
		vo.setRemark(o.getRemark());
		vo.setCreatedAt(o.getCreatedAt());
		vo.setUpdatedAt(o.getUpdatedAt());
		vo.setShop(ShopPacker.toIdName(shop));
		vo.setDeliveryTime(o.getDeliveryTime());
		// delivery man
		Optional.ofNullable(delMan).map(DelManPacker::toHisDelManVo).ifPresent(vo::setDelMan);
	}

	public static MgmtOrderBriefVo toMgmtOrderBriefVo(Order o, Shop shop) {
		final MgmtOrderBriefVo vo = new MgmtOrderBriefVo();
		vo.setId(o.getId());
		vo.setSn(o.getSn());
		vo.setShop(ShopPacker.toIdName(shop));
		vo.setDeliveryTime(o.getDeliveryTime());
		vo.setRemark(o.getRemark());
		return vo;
	}
}